from __base__ import set_django_path

set_django_path()

from lucommon.logger import lu_logger
from app.settings import BASE_DIR
from k8s.core_api import CoreAPI
from utils import execute_cmd

import os
import yaml

"""
监控集群节点变化，更新监控配置
"""


def write_all_yaml(path, data):
    with open(path, 'w') as f:
        yaml.dump_all(data, f, allow_unicode=True)


kubeconfig_path = os.path.join(BASE_DIR, "pem/lts_pem/admin.kubeconfig")

state_metrics_module_path = os.path.join(BASE_DIR,
                                         "module/component/prometheus/serviceMonitor/kube-state-metrics/module")
state_metrics_path = os.path.join(BASE_DIR, "module/component/prometheus/serviceMonitor/kube-state-metrics/")
state_metrics_name = "kube-state-metrics-brood-{env_name}.yaml"

kubelet_metrics_module_path = os.path.join(BASE_DIR,
                                           "module/component/prometheus/serviceMonitor/kubernetes-metrics/module")
kubelet_metrics_path = os.path.join(BASE_DIR, "module/component/prometheus/serviceMonitor/kubernetes-metrics/")
kubelet_metrics_name = "kubelet-metrics-brood-{env_name}.yaml"

node_metrics_module_path = os.path.join(BASE_DIR, "module/component/prometheus/serviceMonitor/node-exporter/module")
node_metrics_path = os.path.join(BASE_DIR, "module/component/prometheus/serviceMonitor/node-exporter/")
node_metrics_name = "node-exporter-brood-{env_name}.yaml"

root_metrics_path = os.path.join(BASE_DIR, "module/component/prometheus/serviceMonitor/")
ingress_metrics_path = os.path.join(BASE_DIR, "module/component/prometheus/serviceMonitor/ingress/")
mysql_metrics_path = os.path.join(BASE_DIR, "module/component/prometheus/serviceMonitor/mysql-exporter/")
nginx_metrics_path = os.path.join(BASE_DIR, "module/component/prometheus/serviceMonitor/nginx-exporter/")

env_map = {
    "stg4": "172.22.75.75",
    "stg18": "172.16.166.31",
    "stg11": "172.22.64.224",
    "stg4-lufunds": "172.22.64.116",
    "qa6": "172.22.65.85",
    "qa6-lufunds": "172.22.64.108",
    "stg27": "172.22.69.211",
    "stg29": "172.22.66.36",
    "base-luagt": "172.22.70.252",
    "me196": "172.22.70.120",
}


def get_node_list(master_ip):
    try:
        with CoreAPI(
                "pem/env_pem/k8s-ca.pem",
                "pem/env_pem/admin.pem",
                "pem/env_pem/admin-key.pem",
                "https://{}:6443".format(master_ip),
        ) as api:
            node_list = list(api.get_nodes().keys())
            lu_logger.info("{}:{}".format(master_ip, "、".join(node_list)))
            return node_list
    except Exception as e:
        lu_logger.error("获取{}集群信息失败".format(master_ip))

        return []


def make_state_metrics_obj(ip, env_name):
    conf_list = []
    f = open(state_metrics_module_path)
    content = f.read()
    content = content.format(env_name=env_name)

    for conf in yaml.load_all(content, Loader=yaml.FullLoader):
        if conf["kind"] == "Endpoints":
            conf["subsets"][0]["addresses"] = [{"ip": ip}]
        conf_list.append(conf)
    write_all_yaml(os.path.join(state_metrics_path, state_metrics_name.format(env_name=env_name)), conf_list)


def make_kubelet_metrics_obj(ip_list, env_name):
    conf_list = []
    f = open(kubelet_metrics_module_path)
    content = f.read()
    content = content.format(env_name=env_name)

    for conf in yaml.load_all(content, Loader=yaml.FullLoader):
        if conf["kind"] == "Endpoints":
            conf["subsets"][0]["addresses"] = [{"ip": ip} for ip in ip_list]
        conf_list.append(conf)
    write_all_yaml(os.path.join(kubelet_metrics_path, kubelet_metrics_name.format(env_name=env_name)), conf_list)


def make_node_exporter_metrics_obj(ip_list, env_name):
    conf_list = []
    f = open(node_metrics_module_path)
    content = f.read()
    content = content.format(env_name=env_name)

    for conf in yaml.load_all(content, Loader=yaml.FullLoader):
        if conf["kind"] == "Endpoints":
            conf["subsets"][0]["addresses"] = [{"ip": ip} for ip in ip_list]
        conf_list.append(conf)
    write_all_yaml(os.path.join(node_metrics_path, node_metrics_name.format(env_name=env_name)), conf_list)


def execute_yaml():
    execute_cmd("kubectl --kubeconfig={} apply -f {}".format(kubeconfig_path, state_metrics_path))
    execute_cmd("kubectl --kubeconfig={} apply -f {}".format(kubeconfig_path, kubelet_metrics_path))
    execute_cmd("kubectl --kubeconfig={} apply -f {}".format(kubeconfig_path, node_metrics_path))

    execute_cmd("kubectl --kubeconfig={} apply -f {}".format(kubeconfig_path, root_metrics_path))
    execute_cmd("kubectl --kubeconfig={} apply -f {}".format(kubeconfig_path, ingress_metrics_path))
    execute_cmd("kubectl --kubeconfig={} apply -f {}".format(kubeconfig_path, mysql_metrics_path))
    execute_cmd("kubectl --kubeconfig={} apply -f {}".format(kubeconfig_path, nginx_metrics_path))


def run():
    for env_name, master_ip in env_map.items():
        node_list = get_node_list(master_ip)
        if not node_list:
            continue
        make_state_metrics_obj(master_ip, env_name)
        make_kubelet_metrics_obj(node_list, env_name)
        make_node_exporter_metrics_obj(node_list, env_name)

    execute_yaml()


if __name__ == '__main__':
    run()
